using AuraUtilities.Configuration;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using Avalonia.Markup.Xaml.Styling;
using Avalonia.Styling;
using Avalonia.Threading;
using LightCAD.Hosting;
using LightCAD.Runtime;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Weikio.PluginFramework.Abstractions;
using Weikio.PluginFramework.Catalogs;

namespace LightCAD.UI
{

    public class LcadApp : Application,IApp
    {

        public static LcadApp Instance { get; private set; }
        public LcadApp()
        {
            Instance = this;
        }

        public static MainWindow ActiveWindow { get; internal set; }



        public bool AllowMultiWindow { get; set; }
        public List<Plugin> Plugins { get; internal set; }
        public List<ILightCADPlugin> PluginInstances { get; internal set; } = new List<ILightCADPlugin>();
        public override void Initialize()
        {
            var settings_prov = new SettingsProvider();
            Settings = settings_prov.Load<AppSettings>();

            switch (Settings.Theme)
            {
                case Theme.Light:
                    Styles.Insert(0, LcadApp.FluentLight);
                    break;

                case Theme.Dark:
                    Styles.Insert(0, LcadApp.FluentDark);
                    break;
            }

            AvaloniaXamlLoader.Load(this);

        }

        public override void OnFrameworkInitializationCompleted()
        {

            MainWindow mainView=null;
            // NavigationViewStatic();
            if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
            {
                AllowMultiWindow = true;
                mainView = WindowManager.CreateWindow();
                desktop.MainWindow = mainView.WindowWrap;

                desktop.Exit += (s, e) =>
                {
                    new SettingsProvider().Save(Settings);
                };
            }
            else if (ApplicationLifetime is ISingleViewApplicationLifetime single)
            {
                AllowMultiWindow = false;
                mainView = WindowManager.CreateWindow();
                single.MainView = mainView;
            }
            
            WindowManager.SetCurrent(mainView);

            this.LoadPlugins();

            if (mainView != null)
            {
               // AppController.Initilize(this, mainView);
            }

            base.OnFrameworkInitializationCompleted();

            Commands.Create();

        }
        private AppSettings Settings
        {
            get;
            set;
        }
        public Theme GetTheme() => Settings.Theme;

        public async Task SetTheme(Theme theme)
        {
            try
            {
                await Dispatcher.UIThread.InvokeAsync(() =>
                {
                    switch (theme)
                    {
                        case Theme.Light:
                            Application.Current.Styles[0] = LcadApp.FluentLight;
                            break;
                        case Theme.Dark:
                            Application.Current.Styles[0] = LcadApp.FluentDark;
                            break;
                    }
                }, (DispatcherPriority)1);

                Settings.Theme = theme;
            }
            catch (Exception)
            {
                Console.WriteLine($"some error has executed");
            }
        }


        private async Task LoadPlugins()
        {
            var folderPluginCatalog = new FolderPluginCatalog(Path.Combine(AppContext.BaseDirectory, "plugins"), type =>
            {
                type.Implements<ILightCADPlugin>();
            });

            await folderPluginCatalog.Initialize();

           this.Plugins = folderPluginCatalog.GetPlugins();
            foreach (var plugin in this.Plugins)
            {
                Console.WriteLine(plugin.Name);
                var instance = (ILightCADPlugin?)Activator.CreateInstance(plugin);
                if (instance != null)
                {
                    instance.Loaded();
                }
                PluginInstances.Add(instance);
            }
        }

        public void OnUIInitilized()
        {
            if(this.Plugins!=null && this.Plugins.Count > 0)
            {
                for (var i = 0; i < this.Plugins.Count; i++)
                {
                    this.PluginInstances[i].InitUI();
                }
            }
        }
       


        public readonly static Styles FluentDark = new Styles
        {
            new StyleInclude(new Uri("avares://Aura.UI.Gallery/Styles"))
            {
                Source = new Uri("avares://Avalonia.Themes.Fluent/FluentDark.xaml")
            },
            new StyleInclude(new Uri("avares://Aura.UI.Gallery/Styles"))
            {
                Source = new Uri("avares://Aura.UI.FluentTheme/AuraUI.xaml")
            }
        };

        public readonly static Styles FluentLight = new Styles
        {
            new StyleInclude(new Uri("avares://Aura.UI.Gallery/Styles"))
            {
                Source = new Uri("avares://Avalonia.Themes.Fluent/FluentLight.xaml")
            },
            new StyleInclude(new Uri("avares://Aura.UI.Gallery/Styles"))
            {
                Source = new Uri("avares://Aura.UI.FluentTheme/AuraUI.xaml")
            }
        };


    }

    [Serializable]
    public class AppSettings : ISettings
    {
        public Theme Theme
        {
            get;
            set;
        }
    }

    [Serializable]
    public enum Theme
    {
        Light,
        Dark
    }

  
}